package nicg.st.service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
import nicg.st.Communicate;
import nicg.st.dao.ResultMapper;
import nicg.st.dao.UserMapper;
import nicg.st.dao.XmlMapper;
import nicg.st.entity.IndicatorDataDetail;
import nicg.st.entity.MyConfig;
import nicg.st.entity.SchemeList;
import nicg.st.entity.SendVO;
import nicg.st.exception.GlobalException;
import nicg.st.outerAPI.OuterInfo;
import nicg.st.util.ErrorCode;
import nicg.st.util.ResponseUtil;
import nicg.st.util.XMLUtil;

/**
 * @author
 * @Description
 * @date 2019/11/3 23:35
 */
@Service
public class XmlService {
	@Autowired
	private XmlMapper xmlMapper;

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private ResultMapper resultMapper;

	@Resource
	MyConfig myConfig;

	private int schemeId;

	/**
	 * @return java.lang.String
	 * @Description 支持用户下载某次评估信息的xml文件
	 * @Date 2019/10/16 14:39
	 * @Param [response]
	 **/
	public String downloadExcel(HttpServletResponse response, int id) {

		SchemeList scheme = xmlMapper.getIndicator(id);
		// 根节点
		Element root = DocumentHelper.createElement("评估方案");
		Document document = DocumentHelper.createDocument(root);
		// 添加评估方案信息
		Element element1 = root.addElement("评估方案信息");
		element1.addElement("id").addText(scheme.getId().toString());
		element1.addElement("name").addText(scheme.getName());
		element1.addElement("user_id").addText(scheme.getUserId().toString());
		element1.addElement("date").addText(scheme.getDate().toString());
		element1.addElement("score").addText(scheme.getScore().toString());
		element1.addElement("report").addText(scheme.getReport());
		element1.addElement("remark").addText(scheme.getRemark());
		element1.addElement("competion").addText(Double.toString(scheme.getCompletion()));
		element1.addElement("deviate").addText(scheme.getDeviate());
		element1.addElement("damage").addText(Double.toString(scheme.getDamage()));
		element1.addElement("conquest").addText(Double.toString(scheme.getConquest()));
		element1.addElement("indicator_id").addText(scheme.getIndicatorId().toString());
		element1.addElement("rwnm").addText(scheme.getRwnm());

		// 添加评估指标数据
		List<IndicatorDataDetail> iddList = xmlMapper.getIndicatorData(id);
		for (IndicatorDataDetail idd : iddList) {
			if (idd.getRelativeWeight() == 0)
				continue;
			Element element2 = root.addElement("评估指标数据");
			element2.addElement("indicator_id").addText(idd.getIndicatorId().toString());
			element2.addElement("indicator_name").addText(idd.getIndicatorName());
			element2.addElement("indicator_path").addText(idd.getIndicatorPath());
			element2.addElement("level").addText(idd.getLevel().toString());
			element2.addElement("relative_weight").addText(idd.getRelativeWeight().toString());
			element2.addElement("score_value").addText(idd.getEntryValue2().toString());
		}
		return XMLUtil.getXMLWriter(response, "PingGuFangAn.xml", document);
	}

	public void listNodes(Element node) {
		Iterator<Element> iterator;
		if (node.getName().equals("评估方案信息")) {
			// System.out.println(String.join("",
			// Collections.nCopies(deep,"----"))+node.getName() + "：" + node.getText());
			SchemeList schemeList = new SchemeList();
			iterator = node.elementIterator();
			node = iterator.next();
			try {
				schemeList.setId(Integer.parseInt(node.getText()));
				node = iterator.next();
				schemeList.setName(node.getText());
				node = iterator.next();
				schemeList.setUserId(Integer.parseInt(node.getText()));
				node = iterator.next();
				schemeList.setDate(new Date());
				node = iterator.next();
				schemeList.setScore(Double.parseDouble(node.getText()));
				node = iterator.next();
				schemeList.setReport(node.getText());
				node = iterator.next();
				schemeList.setRemark(node.getText());
				node = iterator.next();
				schemeList.setCompletion(Double.parseDouble(node.getText()));
				node = iterator.next();
				schemeList.setDeviate(node.getText());
				node = iterator.next();
				schemeList.setDamage(Double.parseDouble(node.getText()));
				node = iterator.next();
				schemeList.setConquest(Double.parseDouble(node.getText()));
				node = iterator.next();
				schemeList.setIndicatorId(Integer.parseInt(node.getText()));
				node = iterator.next();
				schemeList.setRwnm(node.getText());
			} catch (Exception e) {
				System.out.println(e.toString());
			}
			System.out.println(schemeList);
			try {
				System.out.println(schemeList.getName() + "  " + schemeList.getUserId() + "  " + schemeList.getDate()
						+ "  " + schemeList.getScore() + "  " + schemeList.getReport() + "  " + schemeList.getRemark()
						+ "  " + schemeList.getCompletion() + "  " + schemeList.getDeviate() + "  "
						+ schemeList.getDamage() + "  " + schemeList.getConquest() + "  " + schemeList.getIndicatorId()
						+ "  " + schemeList.getRwnm());
				if (schemeList.getRemark() == null)
					schemeList.setRemark("");
				if (schemeList.getReport() == null)
					schemeList.setReport("");
				if (schemeList.getDeviate() == null)
					schemeList.setDeviate("");
				SchemeList ts = new SchemeList(schemeList.getName(), schemeList.getUserId(), new Date(),
						schemeList.getScore(), schemeList.getCompletion(), schemeList.getDeviate(),
						schemeList.getDamage(), schemeList.getConquest(), schemeList.getReport(), "",
						schemeList.getIndicatorId(), schemeList.getRwnm());
				xmlMapper.insertScheme(ts);
			} catch (Exception e) {
				e.printStackTrace();
			}
			schemeId = xmlMapper.getSchemeId();
			System.out.println(schemeId);
		} else if (node.getName().equals("评估指标数据")) {
			IndicatorDataDetail indicatorDataDetail = new IndicatorDataDetail();
			iterator = node.elementIterator();
			try {
				indicatorDataDetail.setSchemeId(schemeId);
				Element node2 = iterator.next();
				indicatorDataDetail.setIndicatorId(Integer.parseInt(node2.getText()));
				node2 = iterator.next();
				indicatorDataDetail.setIndicatorName(node2.getText());
				node2 = iterator.next();
				indicatorDataDetail.setIndicatorPath(node2.getText());
				node2 = iterator.next();
				indicatorDataDetail.setLevel(Integer.parseInt(node2.getText()));
				node2 = iterator.next();
				indicatorDataDetail.setRelativeWeight(Double.parseDouble(node2.getText()));
				indicatorDataDetail.setAbsoluteWeight(0.0);
				indicatorDataDetail.setValue(0.0);
				indicatorDataDetail.setEntryValue1(0.0);
				node2 = iterator.next();
				indicatorDataDetail.setEntryValue2(Double.parseDouble(node2.getText()));
			} catch (Exception e) {
				System.out.println(e.toString());
			}
			xmlMapper.insertIndicatorData(indicatorDataDetail);
		}
		iterator = node.elementIterator();
		while (iterator.hasNext()) {
			Element e = iterator.next();
			listNodes(e);
		}
	}

//    public String downloadWord(HttpServletResponse response, int id) {
//        
//        try {
//        	Map<String, Object> dataMap = new HashMap<>();
//        	
//            SchemeList scheme = xmlMapper.getIndicator(id);
//            
////            Map<String,Object> map1 = new HashMap<String,Object>();
//            // 添加评估方案信息
////            dataMap.put("id", scheme.getId());
//            dataMap.put("name", scheme.getName());
//            String userName=userMapper.selectUserNameById(scheme.getUserId());
//            dataMap.put("userName", userName);
//            dataMap.put("date", scheme.getDate());
//            double score=scheme.getScore();
//            dataMap.put("score",score);
//            
//            if(score>=90) {
//            	dataMap.put("results", "优秀");
//            }else if(score>=75 && score<90) {
//            	dataMap.put("results", "良好");
//            }else if(score>=60 && score<75) {
//            	dataMap.put("results", "一般");
//            }else if(score<60) {
//            	dataMap.put("results", "不合格");
//            }
////            map1.put("report", scheme.getReport());
////            map1.put("remark", scheme.getRemark());
//            
////            List<Map<String,Object>> newlist1 = new ArrayList<>();
////            newlist1.add(map1);
//            
//            List<Map<String,Object>> newlist2 = new ArrayList<>();
//            // 添加评估指标数据
//            List<IndicatorDataDetail> iddList = xmlMapper.getIndicatorData(id);
//            //评估指标名称
//            String indicatorNames=resultMapper.selectIndicatorPathBySchemeId(id);
//            dataMap.put("indicatorNames",indicatorNames);
////            for (IndicatorDataDetail idd : iddList) {
//            for(int i=1;i<iddList.size();i++) {
//            	IndicatorDataDetail idd=iddList.get(i);
//                if (idd.getRelativeWeight() == 0)
//                    continue;
//                Map<String,Object> map2 = new HashMap<String,Object>();
////                map2.put("indicatorId", idd.getIndicatorId());
//                map2.put("indicatorName", idd.getIndicatorName());
//                map2.put("indicatorPath", idd.getIndicatorPath());
////                map2.put("level", idd.getLevel());
//                map2.put("relativeWeight", idd.getRelativeWeight());
//                double score1=idd.getEntryValue2();
//                map2.put("scoreValue", score1);
//                if(score1>=90) {
//                	map2.put("result", "优秀");
//                }else if(score1>=75 && score1<90) {
//                	map2.put("result", "良好");
//                }else if(score1>=60 && score1<75) {
//                	map2.put("result", "一般");
//                }else if(score1<60) {
//                	map2.put("result", "不合格");
//                }
//                newlist2.add(map2);
//            }
//            
//            dataMap.put("indicators", newlist2);
//            
//            System.out.println(dataMap);
//
//            Configuration configuration = new Configuration(new Version("2.3.0"));
//            
//            configuration.setDefaultEncoding("utf-8");
//
//            //指定模板路径
//            configuration.setClassForTemplateLoading(this.getClass(), "/ftl");
//            
//            // 输出文档路径及名称
////            File outFile = new File("F:/test.doc");
//            File outFile = new File("F:/outFile"+Math.random()*1000+".doc");//输出路径
//            //以utf-8的编码读取ftl文件
//            Template t =  configuration.getTemplate("导出模板.ftl","utf-8");
//            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"),10240);
////            response.setContentType("application/xml");
////            response.setHeader("Content-disposition", null);
//            t.process(dataMap, out);
//            out.flush();
//            out.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        
//        return ResponseUtil.getResponseString(ErrorCode.SUCCESSFUL, "successful", "1");
//    }

	public String downloadWord(HttpServletResponse response, int id) {

		try {
			Map<String, Object> dataMap = new HashMap<>();

			SchemeList scheme = xmlMapper.getIndicator(id);

			// 添加评估方案信息
			dataMap.put("name", scheme.getName());
			String userName = userMapper.selectUserNameById(scheme.getUserId());
			dataMap.put("userName", userName);
			dataMap.put("date", scheme.getDate());
			double score = scheme.getScore();
			dataMap.put("score", score);

			if (score >= 90) {
				dataMap.put("results", "优秀");
			} else if (score >= 75 && score < 90) {
				dataMap.put("results", "良好");
			} else if (score >= 60 && score < 75) {
				dataMap.put("results", "一般");
			} else if (score < 60) {
				dataMap.put("results", "不合格");
			}

			List<Map<String, Object>> newlist2 = new ArrayList<>();
			// 添加评估指标数据
			List<IndicatorDataDetail> iddList = xmlMapper.getIndicatorData(id);
			// 评估指标名称
			String indicatorNames = resultMapper.selectIndicatorPathBySchemeId(id);
			dataMap.put("indicatorNames", indicatorNames);
			for (int i = 1; i < iddList.size(); i++) {
				IndicatorDataDetail idd = iddList.get(i);
				if (idd.getRelativeWeight() == 0)
					continue;
				Map<String, Object> map2 = new HashMap<String, Object>();
				map2.put("indicatorName", idd.getIndicatorName());
				map2.put("indicatorPath", idd.getIndicatorPath());
				map2.put("relativeWeight", idd.getRelativeWeight());
				double score1 = idd.getEntryValue2();
				map2.put("scoreValue", score1);
				if (score1 >= 90) {
					map2.put("result", "优秀");
				} else if (score1 >= 75 && score1 < 90) {
					map2.put("result", "良好");
				} else if (score1 >= 60 && score1 < 75) {
					map2.put("result", "一般");
				} else if (score1 < 60) {
					map2.put("result", "不合格");
				}
				newlist2.add(map2);
			}

			dataMap.put("indicators", newlist2);

			System.out.println(dataMap);

			Configuration configuration = new Configuration(new Version("2.3.0"));

			configuration.setDefaultEncoding("utf-8");

			// 指定模板路径
			configuration.setClassForTemplateLoading(this.getClass(), "/ftl");

			// 输出文档路径及名称
			File outFile = new File("测试outFile" + Math.random() * 1000 + ".doc");// 输出路径
			// 以utf-8的编码读取ftl文件
			Template t = configuration.getTemplate("导出模板.ftl", "utf-8");
			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
			t.process(dataMap, out);
			out.flush();
			out.close();

			InputStream fin = new FileInputStream(outFile);

			response.setCharacterEncoding("utf-8");
			response.setContentType("application/msword");
			// 设置浏览器以下载的方式处理该文件名
			String fileName = "outFile" + Math.random() * 1000 + ".doc";
			response.setHeader("Content-disposition",
					"attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));

			OutputStream resout = response.getOutputStream();
			byte[] buffer = new byte[512]; // 缓冲区
			int bytesToRead = -1;
			// 通过循环将读入的Word文件的内容输出到浏览器中
			while ((bytesToRead = fin.read(buffer)) != -1) {
				resout.write(buffer, 0, bytesToRead);
			}
			fin.close();
			outFile.delete();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return ResponseUtil.getResponseString(ErrorCode.SUCCESSFUL, "successful", "1");
	}

	public String getImage(HttpServletRequest request, HttpServletResponse response) {
		String src = request.getParameter("image");
		System.out.println(src);
		String base64 = src.replaceAll(" ", "+");
		String[] arr = base64.split("base64,");
		String image = arr[1];
		System.out.println(image);
		return image;
	}

	public void sendFile(String aimIP) {
//		String filename = "./send.xml";// 文件路径名称
//		String targetIp = "bitcsXml" + aimIP;
//		System.out.println("send Target:  " + targetIp);
//		String sourceIp = "xxzt";// 源ip地址
//		char type = 0x01; // 传输类型
//		MsgTrans1.sendFile_(filename.getBytes(), targetIp.getBytes(), sendCallBack, sourceIp.getBytes(), type, 0, 0, 0);
//		System.out.printf("1111111111111111111111111111111111111111111111");
	}

	public String createDocumentToNative(int id) {
		SchemeList scheme = xmlMapper.getIndicator(id);
		Element root = DocumentHelper.createElement("评估方案");
		Document document = DocumentHelper.createDocument(root);
		Element element1 = root.addElement("评估方案信息");
		element1.addElement("id").addText(scheme.getId().toString());
		element1.addElement("name").addText(scheme.getName());
		element1.addElement("user_id").addText(scheme.getUserId().toString());
		element1.addElement("date").addText(scheme.getDate().toString());
		element1.addElement("score").addText(scheme.getScore().toString());
		element1.addElement("report").addText(scheme.getReport());
		element1.addElement("remark").addText(scheme.getRemark());
		element1.addElement("completion").addText(Double.toString(scheme.getCompletion()));
		element1.addElement("deviate").addText(scheme.getDeviate());
		element1.addElement("damage").addText(Double.toString(scheme.getDamage()));
		element1.addElement("conquest").addText(Double.toString(scheme.getConquest()));
		element1.addElement("indicator_id").addText(scheme.getIndicatorId().toString());
		element1.addElement("rwnm").addText(scheme.getRwnm());

		List<IndicatorDataDetail> iddList = xmlMapper.getIndicatorData(id);
		for (IndicatorDataDetail idd : iddList) {
			if (idd.getRelativeWeight() == 0)
				continue;
			Element element2 = root.addElement("评估指标数据");
			element2.addElement("indicator_id").addText(idd.getIndicatorId().toString());
			element2.addElement("indicator_name").addText(idd.getIndicatorName());
			element2.addElement("indicator_path").addText(idd.getIndicatorPath());
			element2.addElement("level").addText(idd.getLevel().toString());
			element2.addElement("relative_weight").addText(idd.getRelativeWeight().toString());
			element2.addElement("score_value").addText(idd.getEntryValue2().toString());
		}

		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		XMLWriter xmlWriter = null;
		File file = new File("send.xml");
		try {
			xmlWriter = new XMLWriter(new FileOutputStream(file), format);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return ResponseUtil.getResponseString(ErrorCode.ERROR, "error", "UnsupportedEncodingException");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return ResponseUtil.getResponseString(ErrorCode.ERROR, "error", "FileNotFoundException");
		}
		xmlWriter.setEscapeText(false);
		try {
			xmlWriter.write(document);

		} catch (IOException e) {
			e.printStackTrace();
			return ResponseUtil.getResponseString(ErrorCode.ERROR, "error", "IOException");
		} finally {
			if (xmlWriter != null) {
				try {
					xmlWriter.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		System.out.println("生成成功");
		return ResponseUtil.getResponseString(ErrorCode.SUCCESSFUL, "successful", "1");
	}

	public void receiveDocumentToDB(String fileName) {
		System.out.println("receiveDocumentToDB   " + fileName);
		System.out.println(fileName);
		File file = new File(fileName);
		SAXReader reader = new SAXReader();

		Document document = null;
		try {
			document = reader.read(file);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("DocumentException");
		}
		if (null != document) {
			Element root = document.getRootElement();
			listNodes(root);
		}
	}

	/**
	 * 给指定的IP发送评估方案信息指定ID的评估方案信息与评估数据
	 * 
	 * @param targetIp
	 * @param id
	 * @return
	 */
	public String sendBeanToIp(String targetIp, int id) {
		if (Communicate.communicateCode == Communicate.SERVICE_FAILURE) {
			throw new GlobalException("传输服务未成功开启");
		}
		SendVO sendVO = new SendVO();
		SchemeList scheme = xmlMapper.getIndicator(id);
		if (scheme == null) {
			throw new GlobalException("查询id为：" + id + "的评估指标方案信息失败！");
		}
		sendVO.setSchemeList(scheme);
		List<IndicatorDataDetail> dataDetails = new ArrayList<>();
		List<IndicatorDataDetail> iddList = xmlMapper.getIndicatorData(id);
		if (iddList == null || iddList.size() == 0) {
			throw new GlobalException("查询id为：" + id + "的评估指标指标信息失败！");
		}
		for (IndicatorDataDetail idd : iddList) {
			if (idd.getRelativeWeight() == 0) {
				continue;
			} else {
				dataDetails.add(idd);
			}
		}
		sendVO.setDataDetails(dataDetails);
		String userId = OuterInfo.getCurUserId(myConfig.getDtmlServerIp(), myConfig.getDtmlServerPort(),
				myConfig.getDtmlGetCurUserId());
		if (userId == null) {
			throw new GlobalException("获取当前身份信息失败！");
		}
		String myIp = OuterInfo.getUserLoginVehIP(myConfig.getDtmlServerIp(), myConfig.getDtmlServerPort(),
				myConfig.getDtmlGetUserLoginVehIP(), userId);
		if (myIp == null) {
			throw new GlobalException("获取本机IP信息失败");
		}
		int sendCode = OuterInfo.msgCommunicate(myIp, targetIp, sendVO);
		if (sendCode == OuterInfo.ERROR_CODE) {
			throw new GlobalException("发送文件失败");
		}
		return "SUCCESS";
	}

	/**
	 * 将数据插入到数据库中
	 * 
	 * @param jsonData
	 * @return 成功返回SUCCESS
	 */
	public String receiveToDB(String jsonData) {
		SendVO receive = JSONObject.parseObject(jsonData, SendVO.class);
		if (receive == null) {
			throw new GlobalException("获取传输的数据失败");
		}
		SchemeList schemeList = receive.getSchemeList();
		try {
			xmlMapper.insertScheme(schemeList);
		} catch (Exception e) {
			throw new GlobalException("插入指标方案信息时发生错误");
		}
		List<IndicatorDataDetail> indicatorDataDetails = receive.getDataDetails();
		if (indicatorDataDetails == null || indicatorDataDetails.size() == 0) {
			throw new GlobalException("获取传输的指标数据失败");
		}
		int i = 0;
		try {
			for (i = 0; i < indicatorDataDetails.size(); i++) {
				xmlMapper.insertIndicatorData(indicatorDataDetails.get(i));
			}
		} catch (Exception e) {
			throw new GlobalException("插入指标数据时发生错误，错误ID为：" + indicatorDataDetails.get(i).getId());
		}
		return "SUCCESS";
	}
}